package com.cf.simple;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * todo
 *
 * @author Chengfei
 * @date 2020/8/29 15:08
 */
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接对象工厂
        ConnectionFactory factory = new ConnectionFactory();
        //1.1 设置参数
        //ip地址
        factory.setHost("192.168.174.98");
        //tcp端口
        factory.setPort(5672);
        factory.setUsername("itheima");
        factory.setPassword("123");
        factory.setVirtualHost("/itcast");
        //2. 连接对象
        Connection connection = factory.newConnection();
        //3.创建频道
        Channel channel = connection.createChannel();
        /**
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         * 4.创建队列
         * param1 队列名称
         * param2 是否可持久化
         * param3 是否独占该连接
         * param4 是否自动删除
         * param5 其他参数
         */
        String queue = "simple_queue";
        channel.queueDeclare(queue,true,false,false,null);

        //创建消费者,并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            /**
             * consumerTag 消息者标签，在channel.basicConsume时候可以指定
             * envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志(收到消息失败后是否需要重新发送)
             * properties 属性信息
             * body 消息
             */
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                System.out.println("路由key为：" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为：" + envelope.getExchange());
                //消息id
                System.out.println("消息id为：" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("接收到的消息为：" + new String(body, "utf-8"));
            }
        };

        channel.basicConsume(queue, true, consumer);

        //6 不关闭资源
        //channel.close();
        //connection.close();

    }
}
